import SwiftUI

struct LandmarkList: View {
    // The modelData property gets its value automatically, as long as the environment(_:) modifier has been applied to a parent.
    // The @Environment property wrapper enables you to read the model data of the current view.
    @Environment(ModelData.self) var modelData
    // Because you use state properties to hold information that’s specific to a view and its subviews, you always create state as private.
    @State private var showFavoriteOnly = false
    
    var filteredLanmarks: [Landmark] {
        modelData.landmarks.filter { landmark in
            (!showFavoriteOnly || landmark.isFavorite)
        }
    }
    
    var body: some View {
        // Lists work with identifiable data. You can make your data identifiable in one of two ways:
        // by passing along with your data a key path to a property that uniquely identifies each element,
        // by making your data type conform to the Identifiable protocol.
        NavigationSplitView {
            List {
                // You use the $ prefix to access a binding to a state variable, or one of its properties.
                Toggle(isOn: $showFavoriteOnly) {
                    Text("Favorites only")
                }
                
                // To combine static and dynamic views in a list, or to combine two or more different groups of dynamic views
                // use the ForEach type instead of passing your collection of data to List.
                ForEach(filteredLanmarks) { landmark in
                    NavigationLink {
                        LandmarkDetail(landmark: landmark)
                    } label: {
                        LandmarkRow(landmark: landmark)
                    }
                }
            }
            // begins when the filteredLandmarks value changes.
            .animation(.default, value: filteredLanmarks)
            .navigationTitle("Landmarks")
        } detail: {
            // The navigation split view takes a second input that’s a placeholder for the view that appears after someone makes a selection.
            Text("Select a Landmark")
        }
    }
}

#Preview {
    LandmarkList()
        // Adding an environment(_:) modifier passes the data object down through the environment.
        .environment(ModelData())
}
